<template>
  <div>
    <el-card>
      <el-table :data="computedTableData" style="width: 100%">
        <el-table-column label="学生姓名">
          <template #header>
            <el-input v-model="search" placeholder="请输入学生姓名" size="large" :disabled="roleType === 3"/>
          </template>
          <template #default="scope">
            <div style="display: flex; align-items: center">
              {{ scope.row.studentname }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="班级" :filters="computedClass" :filter-method="filterClass" filter-placement="bottom-end">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.class.title }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="综合评分">
          <template #default="scope">
            <el-rate :model-value="getRate(scope.row)" :colors="colors" :allow-half="true" size="large"
              :disabled="true" />
          </template>
        </el-table-column>
        <el-table-column label="评分进度">
          <template #default="scope">
            <el-progress type="circle" :percentage="getPercentage(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-badge :value="getBadge(scope.row)" class="item" :hidden="getBadge(scope.row) === 0">
              <el-button type="primary" round @click="handleRate(scope.row)" style="height: 30px;">评分</el-button>
            </el-badge>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-drawer v-model="outerDrawer" direction="rtl" :size="size">
      <template #header>
        <h2>学生战力评分</h2>
      </template>
      <div>
        <el-button type="primary" :icon="PieChart" round @click="handleView"></el-button>
        <el-divider></el-divider>
        <el-alert type="info" show-icon>
          <span class="text">
            请为<b style="font-size: 20px;">{{ currentItem.studentname }}</b>点亮星星
          </span>
        </el-alert>
        <el-divider></el-divider>
        <!-- <el-scrollbar>
        </el-scrollbar>  -->
        <div v-for="item in tagData" :key="item._id">
          <div class="rate-item">
            <div>{{ item.title }}</div>
            <el-rate :model-value="getItemRate(item.title)" :colors="colors" :allow-half="true"
              @change="handleRateUpdate($event, item.title)" tabindex="-1" :disabled="roleType === 3"/>
          </div>
          <el-divider></el-divider>
        </div>
        <!-- <div v-for="item in tagData" :key="item._id">
          <div class="rate-item">
            <div>{{ item.title }}</div>
            <el-rate :model-value="getItemRate(item.title)" :colors="colors" allow-half
              @change="handleRateEvent($event, item.title)" tabindex="-1" :disabled="roleType === 3" />
          </div>
          <el-divider></el-divider>
        </div> -->
      </div>
    </el-drawer>
    <el-drawer v-model="innerDrawer" title="可视化分析" :before-close="handleClose" size="50%">
      <StudentChart :data="{tableData,currentItem,tagData}" v-if="innerDrawer"></StudentChart>
    </el-drawer>
  </div>
</template>
<script setup>
import axios from 'axios';
import {useRoute} from 'vue-router'
import { ref, onMounted, computed } from 'vue'
import { PieChart } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import StudentChart from '../../components/student-manage/StudentChart.vue';
import useUserStore from '../../store/useUserStore';
const {user:{role:{roleType},username}} = useUserStore()
const colors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])
const tableData = ref([])
const route = useRoute()
const classData = ref([])
const tagData = ref([])
const size = ref("30%")
const search = ref(route.query.name || "")
// const tagList = ref([])
const outerDrawer = ref(false)
const innerDrawer = ref(false)
const currentItem = ref({})
const handleRate = (item) => {
  outerDrawer.value = true
  currentItem.value = item
}
const handleClose = () => {
  innerDrawer.value = false
  size.value = "30%"
}
const handleView = () => {
  innerDrawer.value = true
  size.value = "80%"
}
const getPercentage = ({ score }) => {
  if (tagData.value.length === 0) return 0
  // console.log(Object.keys(score).length/tagData.value.length*100);
  return Math.round(Object.keys(score).length / tagData.value.length * 100)
}
const getRate = ({ score }) => {
  let values = Object.values(score)
  // console.log(values.length);
  let total = values.reduce((t, item) => t + item, 0)
  return total / values.length
}
const getBadge = ({ score }) => {
  // console.log('item',item);
  let keys = Object.keys(score)
  // console.log(keys);
  return tagData.value.length - keys.length
  // if (keys.value) {
  // }else{
  //   return tagData.value.length
  // }
}
const getItemRate = (title) => {
  return tableData.value.filter(item => item._id === currentItem.value._id)[0].score[title]
}
const handleRateUpdate = async (value, title) => {
  await axios.put(`/admin/students/${currentItem.value._id}`, {
    key: title,
    value: value
  })
  ElMessage({
    message: `${currentItem.value.studentname}的${title}评分已经更新`,
    type: 'success'
  })
  await getTableData()
  // location.reload()
}
const handleRateEvent = async (value, title) => {
  // console.log(value)

  await axios.put(`/admin/students/${currentItem.value._id}`, {
    key: title,
    value: value
  })

  ElMessage({
    message: `${currentItem.value.studentname}的${title}评分已经更新`,
    type: 'success',
  })

  await getTableData()
}
const computedClass = computed(() => {
  return classData.value.map(item => ({
    text: item.title,
    value: item._id
  }))
})
onMounted(() => {
  if(roleType === 3){
    search.value = username
  }
  getTableData()
  getClass()
  getTag()
})
const getTag = async () => {
  const res = await axios.get('/admin/tags')
  console.log('tag', res.data);
  tagData.value = res.data
}
const getClass = async () => {
  const res = await axios.get('/admin/classes')
  console.log('class', res.data);
  classData.value = res.data
}
const getTableData = async () => {
  const res = await axios.get('/admin/students')
  console.log('student', res.data);
  tableData.value = res.data
}
//利用计算属性过滤搜索内容
const computedTableData = computed(() => tableData.value.filter(
  item => item.studentname.toLowerCase().includes(search.value.toLowerCase())
))
const filterClass = (value, row, column) => {
  console.log('value', value);
  console.log('row', row);
  console.log('column', column);
  //row._id是学生的id，注意关联class的_id
  return value === row.class._id
}
</script>
<style scoped lang='scss'>
.item {
  margin-top: 9px;
  // margin-right: 20px;
}

.el-card {
  // background-color: aqua;
  border-radius: 30px;

  :deep(.el-table .cell) {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 18px;
    font-weight: bold;
  }
}

.text {
  margin-left: 10px;
  text-align: center;
  font-size: 18px;
  line-height: 44px;
}

.rate-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
}
</style>